package nickthissen.iracing.activities;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.view.View;
import android.widget.Toast;

import nickthissen.iracing.common.*;
import nickthissen.iracing.datamodels.Driver;
import nickthissen.iracing.datamodels.PrivateMessage;
import nickthissen.iracing.datamodels.PrivateMessageItem;
import nickthissen.iracing.datamodels.Result;
import nickthissen.iracing.iracingforum2.R;
import nickthissen.iracing.networking.Networking;
import nickthissen.iracing.parsing.HttpUtil;

public class SendPmActivity extends PostBaseActivity
{
    private static final String DRIVER = "DRIVER";
    private static final String PM_TITLE = "PM_TITLE";
    private static final String TYPE = "TYPE";

	private ProgressDialog dialog;	

	private Driver driver;
	private String title;
	
	public static final int FINDUSER = 1;
		
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        txtTitle.setVisibility(View.VISIBLE);
        txtUser.setVisibility(View.VISIBLE);

        Bundle extras = savedInstanceState;
        if (extras == null)
        {
            Intent i = this.getIntent();
            extras = i.getExtras();
        }
        
        if (type == TYPE_SENDPM)
        {
            this.getSupportActionBar().setTitle("Send a PM");
            btnFindUser.setVisibility(View.VISIBLE);
        	txtUser.setOnClickListener(findUserClickListener);
        	btnFindUser.setOnClickListener(findUserClickListener);

            txtTitle.requestFocus();
        }
        else if (type == TYPE_REPLYPM)
        {
            btnFindUser.setVisibility(View.GONE);

            this.getSupportActionBar().setTitle("Reply to PM");
        	driver = (Driver) extras.getSerializable(DRIVER);
        	title = extras.getString(PM_TITLE);
        	
        	txtUser.setText(driver.Username);
        	txtTitle.setText("Re:" + title);

            txtContent.requestFocus();
        }
    }
	
	@Override
	public void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);
        outState.putSerializable(DRIVER, driver);
        outState.putString(PM_TITLE, title);
	}

    @Override
    protected Task<?> createTask()
    {
        return null;
    }

    @Override
    protected void saveTaskInput(Bundle state)
    {

    }

    @Override
    protected Object restoreTaskInput(Bundle state)
    {
        return null;
    }

    @Override
	public void onRestoreInstanceState(Bundle state)
	{
		driver = (Driver) state.getSerializable(DRIVER);
		title = state.getString(PM_TITLE);
		super.onRestoreInstanceState(state);
	}
	
	public static Intent getIntent(Context context, int type, PrivateMessage pm, PrivateMessageItem pmItem)
	{
		Intent intent = new Intent(context, SendPmActivity.class);
		Bundle extras = new Bundle();
		if (pm != null)
		{
			Driver driver = new Driver();
			driver.Username = pm.From;
			driver.Custid = pm.FromCustid;
			extras.putSerializable(DRIVER, driver);
		}
		if (pmItem != null)
		{
			extras.putString(PM_TITLE, pmItem.Title);
		}
		extras.putInt(TYPE, type);
		intent.putExtras(extras);
		return intent;
	}
	
	private View.OnClickListener findUserClickListener = new View.OnClickListener() {
				@Override
		public void onClick(View v) {
			findUser();
		}
	};
	
	private void findUser()
	{
		Intent intent = new Intent(this, DriverListActivity.class);
		this.startActivityForResult(intent, FINDUSER);
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
	{
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == FINDUSER && resultCode == DriverListActivity.DRIVER_CHOSEN)
        {
        	Bundle bundle = intent.getExtras();
        	driver = (Driver) bundle.getSerializable(DRIVER);
        	txtUser.setText(driver.Username);
        }
	}

	@Override
	protected void onPostButtonClicked()
	{
		if (driver == null)
		{
			Toast.makeText(this, "Please select a user to send to.", Toast.LENGTH_LONG).show();
			return;
		}

		String subject = txtTitle.getText().toString();
		String message = txtContent.getText().toString();
		if (subject.trim().equals(""))
		{
			Toast.makeText(this, "Please submit a subject.", Toast.LENGTH_LONG).show();
			return;
		}

        Pm pm = new Pm();
        pm.title = HttpUtil.htmlEncode(subject);
        pm.message = HttpUtil.htmlEncode(message);
        pm.driver = driver;

        dialog = ProgressDialog.show(this, "Sending", "Your message is being sent...");
        new Task<Pm>(this, poster).execute(pm);
	}

    private DataLoader<Pm> poster = new DataLoader<Pm>()
    {
        @Override
        public Result getData(Pm in)
        {
            return Networking.sendPm(this.getContext(),
                    in.driver.Username,
                    in.driver.Custid,
                    in.title,
                    in.message);
        }

        @Override
        public void onFinished(Result out)
        {
            if (out.Success)
            {
                Toast.makeText(this.getContext(),
                        "Message sent!",
                        Toast.LENGTH_LONG).show();
            }
            else
            {
                nickthissen.iracing.common.Error.fromResult(out).log(this.getContext());

                @SuppressWarnings("deprecation")
                ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                clipboard.setText(txtContent.getText().toString());

                Toast.makeText(this.getContext(),
                        "Error sending message, please try again. Your message has been saved in your clipboard.",
                        Toast.LENGTH_LONG).show();
            }

            postFinished();

            if (dialog != null)
            {
                dialog.dismiss();
                dialog = null;
            }
        }
    };

    private class Pm
    {
        public String title;
        public String message;
        public Driver driver;
    }
}
